const express = require('express');
const router = express.Router();

// 正确引入 db.js：从当前文件（events.js）向上两级目录，找到项目根目录的 db.js
const { query, run } = require('../../db.js'); 

// 报告新事件（POST 请求）- 已正确定义POST路由逻辑
router.post('/', async (req, res) => {
  const { title, description, category, severity, reporter_id } = req.body; 

  // 验证必填项
  if (!title || !category || !reporter_id) { 
    return res.status(400).json({ error: 'Missing required fields (title, category, reporter_id)' });
  }

  // 【新增】验证 severity 字段的范围，假设需要在 1 - 5 之间
  if (severity < 1 || severity > 5) {
    return res.status(400).json({ error: 'Severity must be between 1 and 5' });
  }

  try {
    // 插入事件到 events 表
    const result = await run(
      `INSERT INTO events 
      (title, description, category, severity, reporter_id) 
      VALUES (?, ?, ?, ?, ?)`,
      [title, description, category, severity, reporter_id]
    );

    // 获取刚插入的事件详情
    const newEvent = await query(
      'SELECT * FROM events WHERE id = ?',
      [result.lastID]
    );

    res.status(201).json(newEvent[0]); 
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 更新事件状态（PATCH 请求）
router.patch('/:id/status', async (req, res) => {
  const eventId = req.params.id;
  const { status, assigned_to } = req.body;

  // 验证状态合法性
  const validStatuses = ['reported', 'confirmed', 'in_progress', 'resolved', 'closed']; 
  if (!validStatuses.includes(status)) {
    return res.status(400).json({ error: 'Invalid status. Valid statuses: ' + validStatuses.join(', ') });
  }

  try {
    // 更新事件状态、负责人、更新时间
    await run(
      `UPDATE events SET 
      status = ?, 
      assigned_to = ?, 
      updated_at = datetime('now') 
      WHERE id = ?`,
      [status, assigned_to, eventId]
    );

    // 获取更新后的事件详情
    const updatedEvent = await query(
      'SELECT * FROM events WHERE id = ?',
      [eventId]
    );

    res.json(updatedEvent[0]); 
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;